import axios from "axios";
import { CODE } from "./constants";

const request = axios.create({
    timeout: 5000
})

request.interceptors.response.use(
    response => response,
    error => {
        console.error('global catch error: ', {
            url: error.config?.url,
            method: error.config?.method,
            status: error.response?.status,
            message: error.message
        })
        return Promise.reject(error);
    }
)

export default request;

export class UnauthenticatedError extends Error {
  constructor() {
    super('请先登录获取访问令牌');
    this.statusCode = 401;
    this.name = 'UnauthenticatedError';
  }
}

export const catch_error_resp = (err) => {
    let message = '未知错误';
    if (err instanceof UnauthenticatedError) {
        return { code: err.statusCode, msg: err.message }
    } else if (axios.isCancel(err)) {
        return { code: CODE.REQUEST_CANCEL, msg: '请求取消' };
    } else if (err.response) {
        message = `服务器错误: ${err.response.status}`;
    } else if (err.request) {
        message = '网络异常，请检查连接';
    } else {
        message = err.message || '客户端错误';
    }
    return { code: err.response?.status || CODE.OTHER_ERROR, msg: message };
}

export const wrap_api_func = (fn) => {
  return async (...args) => {
    try {
      return await fn(...args);
    } catch (err) {
      return catch_error_resp(err);
    }
  };
};